/**
 * 财务管理相关Mock数据
 */

import { generateId, randomNumber, randomFloat, randomChoice, randomDate, formatDate, paginate } from '../utils'
import { FINANCE_CONFIG } from '@/config'

// 模拟账户数据
const mockAccounts = [
  {
    id: '1',
    name: '招商银行储蓄卡',
    type: 'bank',
    balance: 15680.50,
    currency: 'CNY',
    description: '主要储蓄账户',
    isDefault: true,
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-15T10:30:00.000Z'
  },
  {
    id: '2',
    name: '支付宝',
    type: 'alipay',
    balance: 2350.80,
    currency: 'CNY',
    description: '日常支付账户',
    isDefault: false,
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-15T09:15:00.000Z'
  },
  {
    id: '3',
    name: '微信钱包',
    type: 'wechat',
    balance: 890.20,
    currency: 'CNY',
    description: '微信支付账户',
    isDefault: false,
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-14T18:45:00.000Z'
  }
]

// 模拟交易记录
const mockTransactions = []

// 模拟预算数据
const mockBudgets = [
  {
    id: '1',
    name: '餐饮预算',
    category: 'food',
    type: 'expense',
    amount: 1500.00,
    spent: 890.50,
    period: 'monthly',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-15T12:00:00.000Z'
  },
  {
    id: '2',
    name: '交通预算',
    category: 'transport',
    type: 'expense',
    amount: 800.00,
    spent: 320.00,
    period: 'monthly',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    isActive: true,
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-15T08:30:00.000Z'
  }
]

// 生成模拟交易记录
function generateTransactions() {
  const categories = [...FINANCE_CONFIG.INCOME_CATEGORIES, ...FINANCE_CONFIG.EXPENSE_CATEGORIES]
  
  for (let i = 0; i < 100; i++) {
    const isIncome = randomChoice([true, false], 1)
    const type = isIncome ? 'income' : 'expense'
    const categoryList = isIncome ? FINANCE_CONFIG.INCOME_CATEGORIES : FINANCE_CONFIG.EXPENSE_CATEGORIES
    const category = randomChoice(categoryList).id
    const account = randomChoice(mockAccounts)
    const amount = isIncome ? randomFloat(1000, 8000, 2) : randomFloat(10, 500, 2)
    const date = randomDate(new Date(2024, 0, 1), new Date())
    
    mockTransactions.push({
      id: generateId(),
      type,
      category,
      accountId: account.id,
      accountName: account.name,
      amount,
      description: generateTransactionDescription(type, category),
      date: formatDate(date, 'YYYY-MM-DD'),
      tags: randomChoice(['工作', '生活', '娱乐', '必需', '可选'], randomNumber(0, 2)),
      location: randomChoice(['北京', '上海', '深圳', '杭州', ''], 1),
      createdAt: date.toISOString(),
      updatedAt: date.toISOString()
    })
  }
  
  // 按日期倒序排列
  mockTransactions.sort((a, b) => new Date(b.date) - new Date(a.date))
}

// 生成交易描述
function generateTransactionDescription(type, category) {
  const descriptions = {
    income: {
      salary: '工资收入',
      bonus: '年终奖金',
      investment: '投资收益',
      part_time: '兼职收入',
      gift: '礼金收入',
      other: '其他收入'
    },
    expense: {
      food: randomChoice(['午餐', '晚餐', '早餐', '下午茶', '聚餐']),
      transport: randomChoice(['地铁', '公交', '打车', '加油', '停车费']),
      shopping: randomChoice(['服装', '数码产品', '日用品', '化妆品', '书籍']),
      entertainment: randomChoice(['电影', '游戏', 'KTV', '旅游', '演出']),
      health: randomChoice(['体检', '药品', '健身', '按摩', '医疗']),
      education: randomChoice(['培训', '书籍', '课程', '考试', '学费']),
      housing: randomChoice(['房租', '物业费', '装修', '家具', '水电费']),
      utilities: randomChoice(['电费', '水费', '燃气费', '网费', '手机费']),
      other: '其他支出'
    }
  }
  
  return descriptions[type][category] || '未知交易'
}

// 初始化交易记录
generateTransactions()

export default {
  // 获取账户列表
  'GET /finance/accounts': async (params = {}) => {
    const { page = 1, pageSize = 20, type, isActive } = params
    
    let filteredAccounts = [...mockAccounts]
    
    // 按类型筛选
    if (type) {
      filteredAccounts = filteredAccounts.filter(account => account.type === type)
    }
    
    // 按状态筛选
    if (isActive !== undefined) {
      filteredAccounts = filteredAccounts.filter(account => account.isActive === isActive)
    }
    
    return paginate(filteredAccounts, page, pageSize)
  },
  
  // 创建账户
  'POST /finance/accounts': async (data) => {
    const { name, type, balance = 0, currency = 'CNY', description, isDefault } = data
    
    // 验证必填字段
    if (!name || !type) {
      throw new Error(JSON.stringify({ code: 1001, message: '账户名称和类型不能为空' }))
    }
    
    // 检查账户名称是否已存在
    if (mockAccounts.find(account => account.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '账户名称已存在' }))
    }
    
    // 如果设置为默认账户，取消其他账户的默认状态
    if (isDefault) {
      mockAccounts.forEach(account => {
        account.isDefault = false
      })
    }
    
    const newAccount = {
      id: generateId(),
      name,
      type,
      balance: parseFloat(balance),
      currency,
      description: description || '',
      isDefault: isDefault || false,
      isActive: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockAccounts.push(newAccount)
    
    return newAccount
  },
  
  // 更新账户
  'PUT /finance/accounts/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const accountIndex = mockAccounts.findIndex(account => account.id === id)
    
    if (accountIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '账户不存在' }))
    }
    
    const allowedFields = ['name', 'type', 'balance', 'currency', 'description', 'isDefault', 'isActive']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 检查名称重复（排除自己）
    if (updates.name && mockAccounts.find(account => account.name === updates.name && account.id !== id)) {
      throw new Error(JSON.stringify({ code: 1004, message: '账户名称已存在' }))
    }
    
    // 如果设置为默认账户，取消其他账户的默认状态
    if (updates.isDefault) {
      mockAccounts.forEach(account => {
        if (account.id !== id) {
          account.isDefault = false
        }
      })
    }
    
    mockAccounts[accountIndex] = {
      ...mockAccounts[accountIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockAccounts[accountIndex]
  },
  
  // 删除账户
  'DELETE /finance/accounts/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const accountIndex = mockAccounts.findIndex(account => account.id === id)
    
    if (accountIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '账户不存在' }))
    }
    
    // 检查是否有关联的交易记录
    const hasTransactions = mockTransactions.some(transaction => transaction.accountId === id)
    if (hasTransactions) {
      throw new Error(JSON.stringify({ code: 1004, message: '该账户存在交易记录，无法删除' }))
    }
    
    mockAccounts.splice(accountIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 获取交易记录
  'GET /finance/transactions': async (params = {}) => {
    const { page = 1, pageSize = 20, type, category, accountId, startDate, endDate } = params
    
    let filteredTransactions = [...mockTransactions]
    
    // 按类型筛选
    if (type) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.type === type)
    }
    
    // 按分类筛选
    if (category) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.category === category)
    }
    
    // 按账户筛选
    if (accountId) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.accountId === accountId)
    }
    
    // 按日期筛选
    if (startDate) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.date >= startDate)
    }
    if (endDate) {
      filteredTransactions = filteredTransactions.filter(transaction => transaction.date <= endDate)
    }
    
    return paginate(filteredTransactions, page, pageSize)
  },
  
  // 创建交易记录
  'POST /finance/transactions': async (data) => {
    const { type, category, accountId, amount, description, date, tags, location } = data
    
    // 验证必填字段
    if (!type || !category || !accountId || !amount) {
      throw new Error(JSON.stringify({ code: 1001, message: '交易类型、分类、账户和金额不能为空' }))
    }
    
    // 验证账户是否存在
    const account = mockAccounts.find(acc => acc.id === accountId)
    if (!account) {
      throw new Error(JSON.stringify({ code: 1003, message: '账户不存在' }))
    }
    
    // 验证金额
    const transactionAmount = parseFloat(amount)
    if (transactionAmount <= 0) {
      throw new Error(JSON.stringify({ code: 1001, message: '金额必须大于0' }))
    }
    
    // 如果是支出，检查账户余额
    if (type === 'expense' && account.balance < transactionAmount) {
      throw new Error(JSON.stringify({ code: 1001, message: '账户余额不足' }))
    }
    
    const newTransaction = {
      id: generateId(),
      type,
      category,
      accountId,
      accountName: account.name,
      amount: transactionAmount,
      description: description || '',
      date: date || formatDate(new Date(), 'YYYY-MM-DD'),
      tags: tags || [],
      location: location || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTransactions.unshift(newTransaction)
    
    // 更新账户余额
    const accountIndex = mockAccounts.findIndex(acc => acc.id === accountId)
    if (accountIndex !== -1) {
      if (type === 'income') {
        mockAccounts[accountIndex].balance += transactionAmount
      } else if (type === 'expense') {
        mockAccounts[accountIndex].balance -= transactionAmount
      }
      mockAccounts[accountIndex].updatedAt = new Date().toISOString()
    }
    
    return newTransaction
  },
  
  // 更新交易记录
  'PUT /finance/transactions/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const transactionIndex = mockTransactions.findIndex(transaction => transaction.id === id)
    
    if (transactionIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '交易记录不存在' }))
    }
    
    const oldTransaction = mockTransactions[transactionIndex]
    const allowedFields = ['type', 'category', 'accountId', 'amount', 'description', 'date', 'tags', 'location']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 如果更新了账户或金额，需要重新计算账户余额
    if (updates.accountId || updates.amount || updates.type) {
      // 恢复原账户余额
      const oldAccount = mockAccounts.find(acc => acc.id === oldTransaction.accountId)
      if (oldAccount) {
        if (oldTransaction.type === 'income') {
          oldAccount.balance -= oldTransaction.amount
        } else if (oldTransaction.type === 'expense') {
          oldAccount.balance += oldTransaction.amount
        }
      }
      
      // 应用新的账户余额
      const newAccountId = updates.accountId || oldTransaction.accountId
      const newAmount = updates.amount || oldTransaction.amount
      const newType = updates.type || oldTransaction.type
      
      const newAccount = mockAccounts.find(acc => acc.id === newAccountId)
      if (!newAccount) {
        throw new Error(JSON.stringify({ code: 1003, message: '新账户不存在' }))
      }
      
      if (newType === 'expense' && newAccount.balance < newAmount) {
        throw new Error(JSON.stringify({ code: 1001, message: '账户余额不足' }))
      }
      
      if (newType === 'income') {
        newAccount.balance += newAmount
      } else if (newType === 'expense') {
        newAccount.balance -= newAmount
      }
      
      updates.accountName = newAccount.name
    }
    
    mockTransactions[transactionIndex] = {
      ...oldTransaction,
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockTransactions[transactionIndex]
  },
  
  // 删除交易记录
  'DELETE /finance/transactions/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const transactionIndex = mockTransactions.findIndex(transaction => transaction.id === id)
    
    if (transactionIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '交易记录不存在' }))
    }
    
    const transaction = mockTransactions[transactionIndex]
    
    // 恢复账户余额
    const account = mockAccounts.find(acc => acc.id === transaction.accountId)
    if (account) {
      if (transaction.type === 'income') {
        account.balance -= transaction.amount
      } else if (transaction.type === 'expense') {
        account.balance += transaction.amount
      }
      account.updatedAt = new Date().toISOString()
    }
    
    mockTransactions.splice(transactionIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 获取预算列表
  'GET /finance/budgets': async (params = {}) => {
    const { page = 1, pageSize = 20, category, type, period, isActive } = params
    
    let filteredBudgets = [...mockBudgets]
    
    // 按分类筛选
    if (category) {
      filteredBudgets = filteredBudgets.filter(budget => budget.category === category)
    }
    
    // 按类型筛选
    if (type) {
      filteredBudgets = filteredBudgets.filter(budget => budget.type === type)
    }
    
    // 按周期筛选
    if (period) {
      filteredBudgets = filteredBudgets.filter(budget => budget.period === period)
    }
    
    // 按状态筛选
    if (isActive !== undefined) {
      filteredBudgets = filteredBudgets.filter(budget => budget.isActive === isActive)
    }
    
    return paginate(filteredBudgets, page, pageSize)
  },
  
  // 创建预算
  'POST /finance/budgets': async (data) => {
    const { name, category, type, amount, period, startDate, endDate } = data
    
    // 验证必填字段
    if (!name || !category || !type || !amount || !period) {
      throw new Error(JSON.stringify({ code: 1001, message: '预算名称、分类、类型、金额和周期不能为空' }))
    }
    
    // 检查预算名称是否已存在
    if (mockBudgets.find(budget => budget.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '预算名称已存在' }))
    }
    
    const newBudget = {
      id: generateId(),
      name,
      category,
      type,
      amount: parseFloat(amount),
      spent: 0,
      period,
      startDate: startDate || formatDate(new Date(), 'YYYY-MM-DD'),
      endDate: endDate || formatDate(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0), 'YYYY-MM-DD'),
      isActive: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockBudgets.push(newBudget)
    
    return newBudget
  },
  
  // 更新预算
  'PUT /finance/budgets/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const budgetIndex = mockBudgets.findIndex(budget => budget.id === id)
    
    if (budgetIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '预算不存在' }))
    }
    
    const allowedFields = ['name', 'category', 'type', 'amount', 'period', 'startDate', 'endDate', 'isActive']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 检查名称重复（排除自己）
    if (updates.name && mockBudgets.find(budget => budget.name === updates.name && budget.id !== id)) {
      throw new Error(JSON.stringify({ code: 1004, message: '预算名称已存在' }))
    }
    
    mockBudgets[budgetIndex] = {
      ...mockBudgets[budgetIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockBudgets[budgetIndex]
  },
  
  // 删除预算
  'DELETE /finance/budgets/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const budgetIndex = mockBudgets.findIndex(budget => budget.id === id)
    
    if (budgetIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '预算不存在' }))
    }
    
    mockBudgets.splice(budgetIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 获取财务统计
  'GET /finance/stats': async (params = {}) => {
    const { period = 'month' } = params
    
    // 计算总资产
    const totalAssets = mockAccounts.reduce((sum, account) => sum + account.balance, 0)
    
    // 计算本月收支
    const now = new Date()
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
    const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    
    const monthTransactions = mockTransactions.filter(transaction => {
      const transactionDate = new Date(transaction.date)
      return transactionDate >= monthStart && transactionDate <= monthEnd
    })
    
    const monthIncome = monthTransactions
      .filter(t => t.type === 'income')
      .reduce((sum, t) => sum + t.amount, 0)
    
    const monthExpense = monthTransactions
      .filter(t => t.type === 'expense')
      .reduce((sum, t) => sum + t.amount, 0)
    
    // 计算预算使用情况
    const activeBudgets = mockBudgets.filter(budget => budget.isActive)
    const totalBudget = activeBudgets.reduce((sum, budget) => sum + budget.amount, 0)
    const totalSpent = activeBudgets.reduce((sum, budget) => sum + budget.spent, 0)
    
    return {
      totalAssets,
      monthIncome,
      monthExpense,
      monthBalance: monthIncome - monthExpense,
      totalBudget,
      totalSpent,
      budgetRemaining: totalBudget - totalSpent,
      budgetUsageRate: totalBudget > 0 ? ((totalSpent / totalBudget) * 100).toFixed(1) : 0,
      accountCount: mockAccounts.length,
      transactionCount: mockTransactions.length,
      budgetCount: activeBudgets.length
    }
  },
  
  // 获取收支分析
  'GET /finance/analysis/income-expense': async (params = {}) => {
    const { period = 'month', year = new Date().getFullYear() } = params
    
    const data = []
    
    if (period === 'month') {
      // 按月统计
      for (let month = 0; month < 12; month++) {
        const monthStart = new Date(year, month, 1)
        const monthEnd = new Date(year, month + 1, 0)
        
        const monthTransactions = mockTransactions.filter(transaction => {
          const transactionDate = new Date(transaction.date)
          return transactionDate >= monthStart && transactionDate <= monthEnd
        })
        
        const income = monthTransactions
          .filter(t => t.type === 'income')
          .reduce((sum, t) => sum + t.amount, 0)
        
        const expense = monthTransactions
          .filter(t => t.type === 'expense')
          .reduce((sum, t) => sum + t.amount, 0)
        
        data.push({
          period: `${year}-${String(month + 1).padStart(2, '0')}`,
          income,
          expense,
          balance: income - expense
        })
      }
    }
    
    return data
  },
  
  // 获取资产负债分析
  'GET /finance/analysis/asset-liability': async () => {
    const assets = mockAccounts
      .filter(account => account.balance > 0)
      .map(account => ({
        name: account.name,
        type: account.type,
        amount: account.balance
      }))
    
    const liabilities = mockAccounts
      .filter(account => account.balance < 0)
      .map(account => ({
        name: account.name,
        type: account.type,
        amount: Math.abs(account.balance)
      }))
    
    const totalAssets = assets.reduce((sum, asset) => sum + asset.amount, 0)
    const totalLiabilities = liabilities.reduce((sum, liability) => sum + liability.amount, 0)
    
    return {
      assets,
      liabilities,
      totalAssets,
      totalLiabilities,
      netWorth: totalAssets - totalLiabilities
    }
  }
}